package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

// allowCORS 设置跨域请求的响应头
func allowCORS(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}

// handleLocations 处理 /CreateLocation 路径的 HTTP 请求
func handleCreateLocations(db *sql.DB, w http.ResponseWriter, r *http.Request) {
	// 允许跨域请求
	allowCORS(w)

	if r.Method == http.MethodOptions {
		return
	}

	if r.Method == "POST" {
		var location struct {
			Name string `json:"name"`
		}
		err := json.NewDecoder(r.Body).Decode(&location)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		defer r.Body.Close()

		// 检查位置名称是否已经存在
		var count int
		err = db.QueryRow("SELECT COUNT(*) FROM locations WHERE name = ?", location.Name).Scan(&count)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if count > 0 {
			http.Error(w, "位置已存在", http.StatusConflict)
			log.Printf("新增位置（%s）已存在", location.Name)
			return
		}

		// 不存在时，将新位置名称插入到数据库中
		_, err = db.Exec("INSERT INTO locations (name) VALUES (?)", location.Name)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusCreated)
		fmt.Fprint(w, "位置名称保存成功")
	} else {
		http.Error(w, "不支持的请求方法", http.StatusMethodNotAllowed)
	}
}

// handleShowLocations 处理 /ShowLocations 路径的 HTTP 请求，用于获取所有位置
func handleShowLocations(db *sql.DB, w http.ResponseWriter, r *http.Request) {
	// 允许跨域请求
	allowCORS(w)

	if r.Method == http.MethodOptions {
		return
	}

	if r.Method == http.MethodGet {
		// 查询 locations 表的所有信息
		rows, err := db.Query("SELECT name FROM locations")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var locations []struct {
			Name string `json:"name"`
		}

		for rows.Next() {
			var name string
			err := rows.Scan(&name)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			locations = append(locations, struct {
				Name string `json:"name"`
			}{Name: name})
		}

		if err = rows.Err(); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(locations)
	} else {
		http.Error(w, "不支持的请求方法", http.StatusMethodNotAllowed)
	}
}
